local extension = Package:new("zhonger_heg_ld")
extension.extensionName = "zhonger_heg"
extension.game_modes_whitelist = {"zhonger_heg_mode"}

local U = require "packages/utility/utility"
local H = require "packages/hegemony/util"

Fk:loadTranslationTable{
  ["zhonger_heg_ld"] = "君临天下",
  ["zhonger_ld_heg"] = "君临",
}

local dengai = General(extension, "zhonger_ld_heg__dengai", "wei", 4)
dengai.mainMaxHpAdjustedValue = -1
local jixi = fk.CreateViewAsSkill{
  name = "zhonger_ld_heg__jixi",
  anim_type = "control",
  pattern = "snatch",
  relate_to_place = "m",
  expand_pile = "dengai_field",
  enabled_at_play = function(self, player)
    return #player:getPile("dengai_field") > 0
  end,
  enabled_at_response = function(self, player)
    return #player:getPile("dengai_field") > 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Self:getPileNameOfId(to_select) == "dengai_field"
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("snatch")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}

local ziliang = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__ziliang",
  anim_type = "support",
  relate_to_place = "d",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and not target.dead and #player:getPile("dengai_field") > 0
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|dengai_field", "#zhonger_ld_heg__ziliang-card::" .. target.id, "dengai_field")
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:moveCardTo(self.cost_data, Card.PlayerHand, target, fk.ReasonGive, self.name, "dengai_field", true, player.id)
  end,
}

dengai:addSkill("m_ex__tuntian")
dengai:addSkill(jixi)
dengai:addSkill(ziliang)

Fk:loadTranslationTable{
  ["zhonger_ld_heg__dengai"] = "邓艾",
  ["#zhonger_ld_heg__dengai"] = "矫然的壮士",
  ["designer:zhonger_ld_heg__dengai"] = "官方",
  ["illustrator:zhonger_ld_heg__dengai"] = "Amo",
  ["zhonger_ld_heg__jixi"] = "急袭",
  [":zhonger_ld_heg__jixi"] = "主将技，此武将牌上的单独阴阳鱼个数-1。你可将一张“田”当【顺手牵羊】使用。",
  ["zhonger_ld_heg__ziliang"] = "资粮",
  [":zhonger_ld_heg__ziliang"] = "副将技，当与你势力相同的角色受到伤害后，你可将一张“田”交给其。",
  ["dengai_field"] = "田",
  ["#zhonger_ld_heg__ziliang-card"] = "资粮：你可将一张“田”交给 %dest",
  ["$zhonger_ld_heg__ziliang1"] = "攻敌之不备，斩将夺辎！",
  ["$zhonger_ld_heg__ziliang2"] = "奇兵正攻，敌何能为？",
  ["$zhonger_ld_heg__jixi1"] = "用兵以险，则战之以胜！",
  ["$zhonger_ld_heg__jixi2"] = "已至马阁山，宜速进军破蜀！",
  ["~zhonger_ld_heg__dengai"] = "君不知臣，臣不知君。罢了……罢了！",
}

local caohong = General(extension, "zhonger_ld_heg__caohong", "wei", 4)

local zhonger_ld_heg__huyuan_active = fk.CreateActiveSkill{
  name = "#zhonger_ld_heg__huyuan_active",
  mute = true,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected, targets)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip
  end,
  target_filter = function(self, to_select, selected, cards)
    return #selected == 0 and #cards == 1 and
      #Fk:currentRoom():getPlayerById(to_select):getAvailableEquipSlots(Fk:getCardById(cards[1]).sub_type) > 0
  end,
  can_use = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:notifySkillInvoked(player, "zhonger_ld_heg__huyuan", "support")
    room:moveCards({
      ids = effect.cards,
      from = player.id,
      to = target.id,
      toArea = Card.PlayerEquip,
      moveReason = fk.ReasonPut,
    })
    local card = Fk:getCardById(effect.cards[1])
    if card.sub_type == Card.SubtypeWeapon then
      player:broadcastSkillInvoke("zhonger_ld_heg__huyuan", 1)
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(target)) do
        if target:distanceTo(p) == 1 and not p:isAllNude() then
          table.insertIfNeed(targets, p.id)
        end
      end
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#zhonger_ld_heg__huyuan-choose::"..target.id, self.name, false)
      if #to > 0 then
        local card = room:askForCardChosen(player, room:getPlayerById(to[1]), "hej", self.name)
        room:throwCard({card}, self.name, room:getPlayerById(to[1]), player)
      end
    elseif card.sub_type == Card.SubtypeArmor then
      player:broadcastSkillInvoke("zhonger_ld_heg__huyuan", 2)
      target:drawCards(1, self.name)
    else
      player:broadcastSkillInvoke("zhonger_ld_heg__huyuan", 3)
      target:drawCards(1, self.name)
    end
  end,
}
local zhonger_ld_heg__huyuan = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__huyuan",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    player.room:askForUseActiveSkill(player, "#zhonger_ld_heg__huyuan_active", "#zhonger_ld_heg__huyuan-invoke", true)
  end,
}
zhonger_ld_heg__huyuan:addRelatedSkill(zhonger_ld_heg__huyuan_active)
caohong:addSkill(zhonger_ld_heg__huyuan)
caohong:addSkill("os__juezhu")
caohong:addRelatedSkill("feiying")



caohong:addCompanions("zhonger_st_heg__caoren")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__caohong"] = "曹洪",
  ["#zhonger_ld_heg__caohong"] = "魏之福将",
  ["designer:zhonger_ld_heg__caohong"] = "官方",
  ["illustrator:zhonger_ld_heg__caohong"] = "官方",
  ["zhonger_ld_heg__huyuan"] = "援护",
  [":zhonger_ld_heg__huyuan"] = "结束阶段开始时，你可以将一张装备牌置于一名角色的装备区里，然后根据此装备牌的种类执行以下效果：<br>"..
  "武器牌：弃置与该角色距离为1的一名角色区域中的一张牌；<br>防具牌、宝物牌或坐骑牌：该角色摸一张牌。",
  ["zhonger_ld_heg__huyuan_active"] = "援护",
  ["#zhonger_ld_heg__huyuan-invoke"] = "援护：你可以将一张装备牌置入一名角色的装备区",
  ["#zhonger_ld_heg__huyuan-choose"] = "援护：弃置 %dest 距离1的一名角色区域中的一张牌",

  ["$zhonger_ld_heg__huyuan1"] = "将军，这件兵器可还趁手？",
  ["$zhonger_ld_heg__huyuan2"] = "刀剑无眼，须得小心防护。",
  ["$zhonger_ld_heg__huyuan3"] = "宝马配英雄！哈哈哈哈……",



  ["cv:zhonger_ld_heg__caohong"] = "官方",
  ["~zhonger_ld_heg__caohong"] = "曹公，可安好...",
}

local jiangwei = General(extension, "zhonger_ld_heg__jiangwei", "shu", 4)
jiangwei:addCompanions("zhonger_st_heg__zhugeliang")
jiangwei.deputyMaxHpAdjustedValue = -1
jiangwei:addSkill("zhuri")
jiangwei:addSkill("yizhi")
jiangwei:addRelatedSkill("hs__guanxing")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__jiangwei"] = "姜维",
  ["#zhonger_ld_heg__jiangwei"] = "炎志灼心",
  ["designer:zhonger_ld_heg__jiangwei"] = "官方",
  ["illustrator:zhonger_ld_heg__jiangwei"] = "西国红云",
  ["$hs__guanxing_zhonger_ld_heg__jiangwei1"] = "天文地理，丞相所教，维铭记于心。",
  ["$hs__guanxing_zhonger_ld_heg__jiangwei2"] = "哪怕只有一线生机，我也不会放弃！",
  ["~zhonger_ld_heg__jiangwei"] = "臣等正欲死战，陛下何故先降……",
}

local jiangfei = General(extension, "zhonger_ld_heg__jiangwanfeiyi", "shu", 3)
local shengxi = fk.CreateTriggerSkill{
  name = "ml__shengxi",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self) and (player.phase == Player.Start or (player.phase == Player.Finish and player:getMark("_ml__shengxi_use-turn") > 0 and player:getMark("_ml__shengxi_damage-turn") == 0))
  end,
  on_cost = function(self, event, target, player, data)
    if player.phase == Player.Start then
      return false
    else
      local choice = player.room:askForChoice(player, {"dismantlement", "nullification", "ex_nihilo", "Cancel"}, self.name, "#ml__shengxi-ask")
      if choice == "Cancel" then
        player:drawCards(1, self.name)
      end
      if choice ~= "Cancel" then
        self.cost_data = choice
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      local id = room:getCardsFromPileByRule(self.cost_data)
      if #id > 0 then
        room:obtainCard(player, id[1], false, fk.ReasonPrey)
      end
  end,

  refresh_events = {fk.PreCardUse, fk.Damage, fk.BeforeCardsMove},
  can_refresh = function(self, event, target, player, data)
    return event == fk.BeforeCardsMove or (player:hasSkill(self.name, true) and player.phase ~= Player.NotActive)
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.PreCardUse then
      player.room:addPlayerMark(player, "_ml__shengxi_use-turn", 1)
    elseif event == fk.Damage then
      player.room:addPlayerMark(player, "_ml__shengxi_damage-turn", 1)
    else
      local hold_areas = {Card.Processing, Card.Void, Card.PlayerHand}
    local mirror_moves = {}
    local ids = {}
    for _, move in ipairs(data) do
      if not table.contains(hold_areas, move.toArea) then
        local move_info = {}
        local mirror_info = {}
        for _, info in ipairs(move.moveInfo) do
          local id = info.cardId
          if Fk:getCardById(id).name == "redistribute" then
            table.insert(mirror_info, info)
            table.insert(ids, id)
          else
            table.insert(move_info, info)
          end
        end
        if #mirror_info > 0 then
          move.moveInfo = move_info
          local mirror_move = table.clone(move)
          mirror_move.to = nil
          mirror_move.toArea = Card.Void
          mirror_move.moveInfo = mirror_info
          table.insert(mirror_moves, mirror_move)
        end
      end
    end
    if #ids > 0 then
      player.room:sendLog{
        type = "#destructDerivedCards",
        card = ids,
      }
    end
    table.insertTable(data, mirror_moves)
    end
  end,
}

jiangfei:addSkill(shengxi)
jiangfei:addSkill("shoucheng")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__jiangwanfeiyi"] = "蒋琬费祎",
  ["#zhonger_ld_heg__jiangwanfeiyi"] = "社稷股肱",
  ["designer:zhonger_ld_heg__jiangwanfeiyi"] = "官方",
  ["ml__shengxi"] = "生息",
  [":ml__shengxi"] = "结束阶段开始时，若你于此回合内使用过牌且没有造成过伤害，你可从牌堆中获得一张你指定的智囊或摸一张牌。" ,
  ["$ml__shengxi1"] = "国之生计，在民生息。",
  ["$ml__shengxi2"] = "安民止战，兴汉室。",
  ["#ml__shengxi-ask"] = "生息：你可获得一种智囊，点取消则摸一张牌",
  ["illustrator:zhonger_ld_heg__jiangwanfeiyi"] = "cometrue",
  ["~zhonger_ld_heg__jiangwanfeiyi"] = "墨守成规，终为其害啊……",
}

local xusheng = General(extension, "zhonger_ld_heg__xusheng", "wu", 4)
xusheng:addSkill("re__pojun")
xusheng:addCompanions("zhonger_st_heg__dingfeng")

Fk:loadTranslationTable{
  ["zhonger_ld_heg__xusheng"] = "徐盛",
  ["#zhonger_ld_heg__xusheng"] = "江东的铁壁",
  ["designer:zhonger_ld_heg__xusheng"] = "官方",
  ["illustrator:zhonger_ld_heg__xusheng"] = "天信",
  ["$re__pojun_zhonger_ld_heg__xusheng1"] = "不怕死，就尽管放马过来",
  ["$re__pojun_zhonger_ld_heg__xusheng2"] = "待末将布下疑城，以退曹贼。",
  ["~zhonger_ld_heg__xusheng"] = "可怜一身胆略，尽随一抔黄土……",
}

local jiangqin = General(extension, "zhonger_ld_heg__jiangqin", "wu", 4)
jiangqin:addSkill("os__shangyi")
jiangqin:addCompanions("zhonger_st_heg__zhoutai")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__jiangqin"] = "蒋钦",
  ["#zhonger_ld_heg__jiangqin"] = "祁奚之器",
  ["designer:zhonger_ld_heg__jiangqin"] = "官方",
  ["illustrator:zhonger_ld_heg__jiangqin"] = "天空之城",
  ["cv:zhonger_ld_heg__jiangqin"] = "官方",
  ["~zhonger_ld_heg__jiangqin"] = "竟破我阵法...",
}

local yuji = General(extension, "zhonger_ld_heg__yuji", "qun", 3)
yuji:addSkill("m_ex__guhuo")
yuji:addRelatedSkill("chanyuan")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__yuji"] = "于吉",
  ["#zhonger_ld_heg__yuji"] = "魂绕左右",
  ["designer:zhonger_ld_heg__yuji"] = "淬毒",
  ["illustrator:zhonger_ld_heg__yuji"] = "G.G.G.",
  ["~zhonger_ld_heg__yuji"] = "幻化之物，终是算不得真呐。",
}

local hetaihou = General(extension, "zhonger_ld_heg__hetaihou", "qun", 3, 3, General.Female)
local zhonger_ld_heg__qiluan = fk.CreateTriggerSkill{
    name = "zhonger_ld_heg__qiluan",
    anim_type = "offensive",
    events = {fk.TurnEnd},
    can_trigger = function(self, event, target, player, data)
      if player:hasSkill(self) then
        local logic = player.room.logic
        local deathevents = logic.event_recorder[GameEvent.Death] or Util.DummyTable
        local turnevents = logic.event_recorder[GameEvent.Turn] or Util.DummyTable
        return #deathevents > 0 and #turnevents > 0 and deathevents[#deathevents].id > turnevents[#turnevents].id
      end
    end,
    on_use = function(self, event, target, player, data)
      local x = 0
      player.room.logic:getEventsOfScope(GameEvent.Death, 1, function (e)
        local deathData = e.data[1]
        if deathData.damage and deathData.damage.from == player then
          x = 3
        else
          x = 1
        end
        return false
      end, Player.HistoryTurn)
      if x > 0 then
        player:drawCards(x, self.name)
      end
    end,
  }
hetaihou:addSkill("zhendu")
hetaihou:addSkill(zhonger_ld_heg__qiluan)
Fk:loadTranslationTable{
  ["zhonger_ld_heg__hetaihou"] = "何太后",
  ["#zhonger_ld_heg__hetaihou"] = "弄权之蛇蝎",
  ["cv:zhonger_ld_heg__hetaihou"] = "水原",
  ["illustrator:zhonger_ld_heg__hetaihou"] = "KayaK&木美人",
  ["designer:zhonger_ld_heg__hetaihou"] = "淬毒",
  ["zhonger_ld_heg__qiluan"] = "戚乱",
  [":zhonger_ld_heg__qiluan"] = "一名角色回合结束时，若本回合有角色死亡，你可摸一张牌（其中若有角色是你杀死的，你改为摸三张牌）。",
  ["$zhonger_ld_heg__qiluan1"] = "待我召吾兄入宫，谁敢不从？",
  ["$zhonger_ld_heg__qiluan2"] = "本后自有哥哥在外照应，有什么好担心的！",
  ["~zhonger_ld_heg__hetaihou"] = "你们男人造的孽，非要说什么红颜祸水……",
}

local lidian = General(extension, "zhonger_ld_heg__lidian", "wei", 3)
lidian:addSkill("xunxun")
lidian:addSkill("wangxi")
lidian:addCompanions("zhonger_st_heg__yuejin")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__lidian"] = "李典",
  ["#zhonger_ld_heg__lidian"] = "深明大义",
  ["designer:zhonger_ld_heg__lidian"] = "KayaK",
  ["illustrator:zhonger_ld_heg__lidian"] = "张帅",
  ["~zhonger_ld_heg__lidian"] = "报国杀敌，虽死犹荣……",
}

local zangba = General(extension, "zhonger_ld_heg__zangba", "wei", 4)
local hengjiang = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__hengjiang",
  anim_type = "masochism",
  events = { fk.Damaged },
  can_trigger = function(self, _, target, player, _)
    if target ~= player or not player:hasSkill(self) then return false end
    local current = player.room.current
    return current ~= nil and not current.dead
  end,
  on_use = function(_, _, _, player, data)
    local room = player.room
    local target = room.current
    if target ~= nil and not target.dead then
      player:drawCards(1)
      room:doIndicate(player.id, {target.id})
      room:addPlayerMark(target, "@hengjiang-turn", data.damage)
      room:addPlayerMark(target, MarkEnum.MinusMaxCardsInTurn, data.damage)
    end
  end
}
zangba:addSkill(hengjiang)
zangba:addCompanions("zhonger_st_heg__zhangliao")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__zangba'] = '臧霸',
  ["#zhonger_ld_heg__zangba"] = "节度青徐",
  ["illustrator:zhonger_ld_heg__zangba"] = "HOOO",
  ["cv:zhonger_ld_heg__zangba"] = "墨禅",
  ['zhonger_ld_heg__hengjiang'] = '横江',
  [':zhonger_ld_heg__hengjiang'] = '当你受到1点伤害后，你可以令当前回合角色本回合手牌上限-1，然后你摸一张牌。',
  ['$zhonger_ld_heg__hengjiang1'] = '霸必奋勇杀敌，一雪夷陵之耻！',
  ['$zhonger_ld_heg__hengjiang2'] = '江横索寒，阻敌绝境之中！',
  ['~zhonger_ld_heg__zangba'] = '断刃沉江，负主重托……',
}

local madai = General(extension, "zhonger_ld_heg__madai", "shu", 4)
madai:addSkill("heg_madai__mashu")
madai:addSkill("re__qianxi")
madai:addCompanions("zhonger_st_heg__machao")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__madai"] = "马岱",
  ["#zhonger_ld_heg__madai"] = "临危受命",
  ["designer:zhonger_ld_heg__madai"] = "官方",
  ["illustrator:zhonger_ld_heg__madai"] = "Thinking",
  ["heg_madai__mashu"] = "马术",
  [":heg_madai__mashu"] = "锁定技，你与其他角色的距离-1。",
  ["~zhonger_ld_heg__madai"] = "我怎么会死在这里……",
}

local mifuren = General(extension, "zhonger_ld_heg__mifuren", "shu", 3, 3, General.Female)
mifuren:addSkill("guixiu")
mifuren:addSkill("cunsi")
mifuren:addRelatedSkill("yongjue")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__mifuren'] = '糜夫人',
  ["#zhonger_ld_heg__mifuren"] = "乱世沉香",
  ["designer:zhonger_ld_heg__mifuren"] = "淬毒",
  ["illustrator:zhonger_ld_heg__mifuren"] = "木美人",
  ["~zhonger_ld_heg__mifuren"] = "阿斗被救，妾身再无牵挂…",
}

local sunce = General(extension, "zhonger_ld_heg__sunce", "wu", 4)
sunce.deputyMaxHpAdjustedValue = -1
sunce:addCompanions { "zhonger_st_heg__zhouyu", "zhonger_st_heg__taishici", "zhonger_st_heg__daqiao" }
sunce:addSkill("mou__jiang")
local hunshang = fk.CreateTriggerSkill{
  name = 'zhonger_ld_heg__hunshang',
  relate_to_place = 'd',
  events = {fk.EventPhaseStart},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player.phase == Player.Start and player.hp == 1
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:handleAddLoseSkills(player, 'heg_yingzi|heg_yinghun')
    local logic = room.logic
    logic:getCurrentEvent():findParent(GameEvent.Turn):addExitFunc(function()
      room:handleAddLoseSkills(player, '-heg_yingzi|-heg_yinghun')
    end)
  end,
}
sunce:addSkill(hunshang)
local yingzi = fk.CreateTriggerSkill{
  name = "heg_yingzi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  on_use = function(self, event, target, player, data)
    data.n = data.n + 1
  end,
}
local yingzi_maxcards = fk.CreateMaxCardsSkill{
  name = "#heg__yingzi_maxcards",
  fixed_func = function(self, player)
    if player:hasSkill(self) then
      return player.maxHp
    end
  end
}
yingzi:addRelatedSkill(yingzi_maxcards)
sunce:addRelatedSkill(yingzi)
local yinghun = fk.CreateTriggerSkill{
  name = "heg_yinghun",
  anim_type = "drawcard",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and player:isWounded()
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#yinghun-choose:::"..player:getLostHp()..":"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local n = player:getLostHp()
    local choice = room:askForChoice(player, {"#yinghun-draw:::" .. n,  "#yinghun-discard:::" .. n}, self.name)
    if choice:startsWith("#yinghun-draw") then
      player:broadcastSkillInvoke(self.name, 1)
      room:notifySkillInvoked(player, self.name, "support")
      to:drawCards(n, self.name)
      room:askForDiscard(to, 1, 1, true, self.name, false)
    else
      player:broadcastSkillInvoke(self.name, 2)
      room:notifySkillInvoked(player, self.name, "control")
      to:drawCards(1, self.name)
      room:askForDiscard(to, n, n, true, self.name, false)
    end
  end,
}
sunce:addRelatedSkill(yinghun)
Fk:loadTranslationTable{
  ['zhonger_ld_heg__sunce'] = '孙策',
  ["#zhonger_ld_heg__sunce"] = "江东的小霸王",
  ["designer:zhonger_ld_heg__sunce"] = "KayaK（韩旭）",
  ["illustrator:zhonger_ld_heg__sunce"] = "木美人",
  ['zhonger_ld_heg__hunshang'] = '魂殇',
  [':zhonger_ld_heg__hunshang'] = '副将技，锁定技，此武将牌减少半个阴阳鱼；准备阶段，若你的体力值为1，你拥有技能“英姿”和“英魂”至本回合结束。',
  ['heg_yingzi'] = '英姿',
  [":heg_yingzi"] = "锁定技，摸牌阶段，你多摸一张牌；你的手牌上限等于你的体力上限。",
  ["heg_yinghun"] = "英魂",
  [":heg_yinghun"] = "准备阶段，你可选择一名其他角色并选择一项：1.令其摸X张牌，然后弃置一张牌；2.令其摸一张牌，然后弃置X张牌（X为你已损失的体力值）。",
  ["$heg_yingzi1"] = "得公瑾辅助，策定当一战！",
  ["$heg_yingzi2"] = "公瑾在此，此战无忧！",
  ["$zhonger_ld_heg__hunshang1"] = "江东新秀，由此崛起。",
  ["$zhonger_ld_heg__hunshang2"] = "看汝等大展英气！",
  ["$heg_yinghun1"] = "东吴繁盛，望父亲可知。",
  ["$heg_yinghun2"] = "父亲，吾定不负你期望！",
  ["~zhonger_ld_heg__sunce"] = "大志未展，权弟当继……",
}

local chengdong = General(extension, "zhonger_ld_heg__chenwudongxi", "wu", 4)
chengdong:addSkill("os__yilie")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__chenwudongxi'] = '陈武董袭',
  ["#zhonger_ld_heg__chenwudongxi"] = "壮怀激烈",
  ["designer:zhonger_ld_heg__chenwudongxi"] = "淬毒",
  ["illustrator:zhonger_ld_heg__chenwudongxi"] = "地狱许",
  ["~zhonger_ld_heg__chenwudongxi"] = "杀身卫主，死而无憾！",
}

local dongzhuo = General(extension, "zhonger_ld_heg__dongzhuo", "qun", 4)
dongzhuo:addSkill("jiuchi")
dongzhuo:addSkill("roulin")
dongzhuo:addSkill("baoling")
dongzhuo:addRelatedSkill("benghuai")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__dongzhuo'] = '董卓',
  ["#zhonger_ld_heg__dongzhuo"] = "魔王",
  ["designer:zhonger_ld_heg__dongzhuo"] = "KayaK（韩旭）",
  ["illustrator:zhonger_ld_heg__dongzhuo"] = "巴萨小马",
  ['~zhonger_ld_heg__dongzhuo'] = '为何人人……皆与我为敌？',
}

local zhangren = General(extension, "zhonger_ld_heg__zhangren", "qun", 4)

local zhonger_ld_heg__chuanxin = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__chuanxin",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:usedSkillTimes(self.name, Player.HistoryRound) > 0 then return false end
    return player:hasSkill(self) and target.phase == Player.Finish and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local success, dat = player.room:askForUseActiveSkill(player, "zhonger_ld_heg__chuanxin_viewas", "#zhonger_ld_heg__chuanxin-invoke", true)
    if success then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk.skills["zhonger_ld_heg__chuanxin_viewas"]:viewAs(self.cost_data.cards)
    local n = 0
    room.logic:getEventsOfScope(GameEvent.Recover, 999, function(e)
      local recover = e.data[1]
      for _, id in ipairs(self.cost_data.targets) do
        if recover.who.id == id then
          n = n + 0
        end
      end
    end, Player.HistoryTurn)
    local use = {
      from = player.id,
      tos = table.map(self.cost_data.targets, function(id) return {id} end),
      card = card,
      extraUse = true,
      additionalDamage = n,
    }
    room:useCard(use)
  end,
}
local zhonger_ld_heg__chuanxin_viewas = fk.CreateViewAsSkill{
  name = "zhonger_ld_heg__chuanxin_viewas",
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card:addSubcards(cards)
    card.skillName = "zhonger_ld_heg__chuanxin"
    return card
  end,
}
Fk:addSkill(zhonger_ld_heg__chuanxin_viewas)
zhangren:addSkill(zhonger_ld_heg__chuanxin)

Fk:loadTranslationTable{
  ['zhonger_ld_heg__zhangren'] = '张任',
  ["#zhonger_ld_heg__zhangren"] = "索命神射",
  ["designer:zhonger_ld_heg__zhangren"] = "淬毒",
  ["illustrator:zhonger_ld_heg__zhangren"] = "DH",
  ["zhonger_ld_heg__chuanxin"] = "穿心",
  ["$zhonger_ld_heg__chuanxin1"] = "一箭穿心，哪里可逃？",
  ["$zhonger_ld_heg__chuanxin2"] = "穿心之痛，细细品吧，哈哈哈哈！",
  ["zhonger_ld_heg__chuanxin_viewas"] = "穿心",
  [":zhonger_ld_heg__chuanxin"] = "每轮限一次，一名角色的结束阶段，你可以将一张牌当【杀】使用。",
  ["#zhonger_ld_heg__chuanxin-invoke"] = "穿心：你可以将一张牌当【杀】使用。",
  ['~zhonger_ld_heg__zhangren'] = '本将军败于诸葛，无憾……',
}

local xunyou = General(extension, "zhonger_ld_heg__xunyou", "wei", 3)
xunyou:addSkill("ld__qice")
xunyou:addSkill("zhiyu")
xunyou:addCompanions("zhonger_st_heg__xunyu")

Fk:loadTranslationTable{
  ["zhonger_ld_heg__xunyou"] = "荀攸",
  ["#zhonger_ld_heg__xunyou"] = "曹魏的谋主",
  ["designer:zhonger_ld_heg__xunyou"] = "淬毒",
  ["illustrator:zhonger_ld_heg__xunyou"] = "心中一凛",
  ["~zhonger_ld_heg__xunyou"] = "主公，臣下……先行告退……",
}


local bianfuren = General(extension, "zhonger_ld_heg__bianfuren", "wei", 3)
local yuejian = fk.CreateActiveSkill{
  name = "zhonger_ld_heg__yuejian",
  anim_type = "support",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1 and player:getHandcardNum() > player:getMaxCards()
  end,
  card_num = function() return Self:getHandcardNum() - Self:getMaxCards() end,
  card_filter = function(self, to_select, selected)
    return #selected < Self:getHandcardNum() - Self:getMaxCards()
  end,
  target_num = 0,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local num = #effect.cards
    room:moveCardTo(effect.cards, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, false)
    room:askForGuanxing(player, room:getNCards(num), nil, nil, "os__yuejianPut", false) --不会更新牌堆牌数！
    room:doBroadcastNotify("UpdateDrawPile", #room.draw_pile) --手动……
    if num > 0 then
      room:addPlayerMark(player, MarkEnum.AddMaxCards)
    end
    if num > 1 then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      })
    end
    if num > 2 then
      room:changeMaxHp(player, 0)
    end
  end,
}
bianfuren:addCompanions("zhonger_st_heg__caocao")
bianfuren:addSkill("ld__wanwei")
bianfuren:addSkill(yuejian)

Fk:loadTranslationTable{
  ["zhonger_ld_heg__bianfuren"] = "卞夫人",
  ["#zhonger_ld_heg__bianfuren"] = "奕世之雍容",
  ["illustrator:zhonger_ld_heg__bianfuren"] = "雪君S",
  ["zhonger_ld_heg__yuejian"] = "约俭",
  [":zhonger_ld_heg__yuejian"] = "出牌阶段限一次，你可以将X张牌置于牌堆顶或牌堆底（X为你手牌数减去手牌上限的差且至少为1），若因此失去的牌数不小于：1，你的手牌上限+1；2，你回复1点体力。",
  ["$zhonger_ld_heg__yuejian1"] = "吾母仪天下，于节俭处当率先垂范。",
  ["$zhonger_ld_heg__yuejian2"] = "取上为贪，取下为伪，妾则取其中者。",
  ["~zhonger_ld_heg__bianfuren"] = "子桓，兄弟之情，不可轻忘…",
}

local shamoke = General(extension, "zhonger_ld_heg__shamoke", "shu", 4)
local zhonger_ld_heg__jilis = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__jilis",
  anim_type = "drawcard",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      local x, y = 3, player:getMark("zhonger_ld_heg__jilis_times-turn")
      if x >= y then
        local room = player.room
        local logic = room.logic
        local end_id = player:getMark("zhonger_ld_heg__jilis_record-turn")
        local e = logic:getCurrentEvent()
        if end_id == 0 then
          local turn_event = e:findParent(GameEvent.Turn, false)
          if turn_event == nil then return false end
          end_id = turn_event.id
        end
        room:setPlayerMark(player, "zhonger_ld_heg__jilis_record-turn", logic.current_event_id)
        local events = logic.event_recorder[GameEvent.UseCard] or Util.DummyTable
        for i = #events, 1, -1 do
          e = events[i]
          if e.id <= end_id then break end
          local use = e.data[1]
          if use.from == player.id then
            y = y + 1
          end
        end
        room:setPlayerMark(player, "zhonger_ld_heg__jilis_times-turn", y)
        return x == y
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
  end,
}
shamoke:addSkill(zhonger_ld_heg__jilis)
Fk:loadTranslationTable{
  ['zhonger_ld_heg__shamoke'] = '沙摩柯',
  ["#zhonger_ld_heg__shamoke"] = "五溪蛮王",
  ["illustrator:zhonger_ld_heg__shamoke"] = "LiuHeng",
  ["designer:zhonger_ld_heg__shamoke"] = "韩旭",
  ["zhonger_ld_heg__jilis"] = "蒺藜",
  [":zhonger_ld_heg__jilis"] = "当你于一回合内使用第三张牌时，你可以摸两张牌。",
  ['~zhonger_ld_heg__shamoke'] = '五溪蛮夷，不可能输！',
  ["$zhonger_ld_heg__jilis1"] = "蒺藜骨朵，威震慑敌！",
  ["$zhonger_ld_heg__jilis2"] = "看我一招，铁蒺藜骨朵！",
}

local masu = General(extension, "zhonger_ld_heg__masu", "shu", 3)
masu:addSkill("sanyao")
masu:addSkill("ld__zhiman")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__masu'] = '马谡',
  ["#zhonger_ld_heg__masu"] = "帷幄经谋",
  ["designer:zhonger_ld_heg__masu"] = "点点",
  ["illustrator:zhonger_ld_heg__masu"] = "蚂蚁君",
  ["~zhonger_ld_heg__masu"] = "败军之罪，万死难赎……" ,
}

local lingtong = General(extension, "zhonger_ld_heg__lingtong", "wu", 4)
lingtong:addSkill("xuanlve")
lingtong:addSkill("yongjin")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__lingtong'] = '凌统',
  ["#zhonger_ld_heg__lingtong"] = "豪情烈胆",
  ["designer:zhonger_ld_heg__lingtong"] = "韩旭",
  ["illustrator:zhonger_ld_heg__lingtong"] = "F.源",
  ["~zhonger_ld_heg__lingtong"] = "大丈夫，不惧死亡……",
}

local lvfan = General(extension, "zhonger_ld_heg__lvfan", "wu", 3)
lvfan:addCompanions("zhonger_ld_heg__sunce")
lvfan:addSkill("yanji")
lvfan:addSkill("diancai")

Fk:loadTranslationTable{
  ['zhonger_ld_heg__lvfan'] = '吕范',
  ["#zhonger_ld_heg__lvfan"] = "忠笃亮直",
  ["designer:zhonger_ld_heg__lvfan"] = "韩旭",
  ["illustrator:zhonger_ld_heg__lvfan"] = "铭zmy",
  ["~zhonger_ld_heg__lvfan"] = "闻主公欲授大司马之职，容臣不能……谢恩了……",
}

local zuoci = General(extension, "zhonger_ld_heg__zuoci", "qun", 3)
---@param player ServerPlayer
local addxinshengSkill = function(player, skillName)
  local room = player.room
  local skill = Fk.skills[skillName]
  if (not skill) or skill.lordSkill or skill.switchSkillName
    or skill.frequency > 3 -- 锁定技=3 后面的都是特殊标签
    or player:hasSkill(skill, true) then
    return
  end

  local xinsheng_skills = player:getMark("js_xinsheng_skills")
  if xinsheng_skills == 0 then xinsheng_skills = {} end
  table.insert(xinsheng_skills, skillName)
  room:setPlayerMark(player, "js_xinsheng_skills", xinsheng_skills)

  --[[
  -- room:handleAddLoseSkills(player, skillName, nil, false)
  player:doNotify("AddSkill", json.encode{ player.id, skillName })

  if skill:isInstanceOf(TriggerSkill) or table.find(skill.related_skills,
    function(s) return s:isInstanceOf(TriggerSkill) end) then
    player:doNotify("AddSkill", json.encode{ player.id, skillName, true })
  end

  if skill.frequency ~= Skill.Compulsory then
  end
  --]]

  player:addFakeSkill(skill)
  player:prelightSkill(skill.name, true)
end

---@param player ServerPlayer
local removexinshengSkill = function(player, skillName)
  local room = player.room
  local skill = Fk.skills[skillName]

  local xinsheng_skills = player:getMark("js_xinsheng_skills")
  if xinsheng_skills == 0 then return end
  if not table.contains(xinsheng_skills, skillName) then
    return
  end
  table.removeOne(xinsheng_skills, skillName)
  room:setPlayerMark(player, "js_xinsheng_skills", xinsheng_skills)

  --[[
  if player:hasSkill(skillName) then -- FIXME: 预亮的bug，预亮技能会导致服务器为玩家直接添加技能
    player:loseSkill(Fk.skills[skillName])
  end
  player:doNotify("LoseSkill", json.encode{ player.id, skillName })

  if skill:isInstanceOf(TriggerSkill) or table.find(skill.related_skills,
    function(s) return s:isInstanceOf(TriggerSkill) end) then
    player:doNotify("LoseSkill", json.encode{ player.id, skillName, true })
  end
  --]]

  player:loseFakeSkill(skill)
end

---@param player ServerPlayer
---@param general General
local function addxinsheng(player, general, addSkill)
  local room = player.room
  local glist = U.getMark(player, "@&js_xinsheng")
  table.insertIfNeed(glist, general.name)
  room:setPlayerMark(player, "@&js_xinsheng", glist)

  if not addSkill then return end
  for _, s in ipairs(general.skills) do
    addxinshengSkill(player, s.name)
  end
  for _, sname in ipairs(general.other_skills) do
    addxinshengSkill(player, sname)
  end
end

local banned_xinsheng = {
  "starsp__xiahoudun",  -- 原因：无敌
  "shichangshi",   -- 原因：变将与休整
  "godjiaxu", "zhangfei","js__huangzhong", "liyixiejing", "olz__wangyun", "yanyan", "duanjiong", "wolongfengchu", "wuanguo",
  "os__wangling", -- 原因：没有可用技能
  "js__pangtong", "os__xia__liubei", -- 原因：发动技能逻辑缺陷
}

local zhonger_ld_heg__xinsheng_trigger = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__xinsheng_trigger",
  events = {fk.GameStart, fk.TurnStart},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, _)
    if event == fk.GameStart then
      return 1 > 2
    else
      return target == player and player:hasSkill(self) and #U.getMark(player, "@&js_xinsheng") < 4
    end
  end,
  on_use = function(self, _, _, player, _)
    local room = player.room
    local exclude_list = table.map(room.players, function(p)
      return p.general
    end)
    table.insertTable(exclude_list, banned_xinsheng)
    for _, p in ipairs(room.players) do
      local deputy = p.deputyGeneral
      if deputy and deputy ~= "" then
        table.insert(exclude_list, deputy)
      end
    end

    local m = player:getMark("@&js_xinsheng")
    local n = 4 - #U.getMark(player, "@&js_xinsheng")
    local generals = Fk:getGeneralsRandomly(n, nil, exclude_list)
    for _, g in ipairs(generals) do
      addxinsheng(player, g, player:hasSkill("zhonger_ld_heg__xinsheng"))
    end
  end,

  refresh_events = {fk.SkillEffect},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("js_xinsheng_skills") ~= 0 and
      table.contains(player:getMark("js_xinsheng_skills"), data.name)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    for _, s in ipairs(data.related_skills) do
      if s:isInstanceOf(StatusSkill) then
        room.status_skills[s.class] = room.status_skills[s.class] or {}
        table.insertIfNeed(room.status_skills[s.class], s)
        room:doBroadcastNotify("AddSkill", json.encode{player.id, s.name})
      end
    end
  end,
}

zuoci:addSkill(zhonger_ld_heg__xinsheng_trigger)

---@param player ServerPlayer
---@param general_name string
local function removexinsheng(player, general_name)
  local room = player.room
  local glist = player:getMark("@&js_xinsheng")
  if glist == 0 then return end
  table.removeOne(glist, general_name)
  room:setPlayerMark(player, "@&js_xinsheng", #glist > 0 and glist or 0)

  local general = Fk.generals[general_name]
  for _, s in ipairs(general.skills) do
    removexinshengSkill(player, s.name)
  end
  for _, sname in ipairs(general.other_skills) do
    removexinshengSkill(player, sname)
  end
end

local pingjian = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__xinsheng",
  events = {fk.AfterSkillEffect},
  can_trigger = function(self, _, target, player, data)
    return target == player and player:hasSkill(self) and #U.getMark(player, "@&js_xinsheng") > 0
      and player:getMark("js_xinsheng_skills") ~= 0 and
      table.contains(player:getMark("js_xinsheng_skills"), data.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, _, target, player, data)
    local room = player.room
    local choices = player:getMark("@&js_xinsheng")
    local owner = table.find(choices, function (name)
      local general = Fk.generals[name]
      return table.contains(general:getSkillNameList(), data.name)
    end) or "?"
    local choice = choices[1]
    if #choices > 1 then
      local result = player.room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
        choices,
        {"OK"},
        "#js_lose_xinsheng:::"..owner,
      })
      if result ~= "" then
        local reply = json.decode(result)
        choice = reply.cards[1]
      end
    end
    removexinsheng(player, choice)
  end,

  refresh_events = {fk.EventLoseSkill},
  can_refresh = function (self, event, target, player, data)
    return target == player and data == self and player:getMark("@&js_xinsheng") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    for _, g in ipairs(player:getMark("@&js_xinsheng")) do
      removexinsheng(player, g)
    end
  end,
}
zuoci:addSkill(pingjian)



zuoci:addCompanions("zhonger_ld_heg__yuji")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__zuoci"] = "左慈",
  ["#zhonger_ld_heg__zuoci"] = "鬼影神道",
  ["illustrator:zhonger_ld_heg__zuoci"] = "吕阳",
  ["zhonger_ld_heg__xinsheng_trigger"] = "汲魂",
  [":zhonger_ld_heg__xinsheng_trigger"] = "锁定技，回合开始前，若你的“魂”少于四张，则你从剩余武将牌堆中将“魂”补至四张。",
  ["@&js_xinsheng"] = "魂",
  ["#js_lose_xinsheng"] = "请移除一张“魂”",
  ["zhonger_ld_heg__xinsheng"] = "役鬼",
  [":zhonger_ld_heg__xinsheng"] = "当“魂”上的无类型标签或者只有锁定技标签的技能满足发动时机时，你可以发动该技能。"..
  "此技能的效果结束后，你须移除一张“魂”。",
  ["$zhonger_ld_heg__xinsheng_trigger1"] = "世间万物，贫道皆可化为其形。",
  ["$zhonger_ld_heg__xinsheng_trigger2"] = "尘身土塑，唯魂魄难得。",
  ["$zhonger_ld_heg__xinsheng1"] = "大成若缺，损益无妨。",
  ["$zhonger_ld_heg__xinsheng2"] = "大盈若冲，心神自现。",
  ["~zhonger_ld_heg__zuoci"] = "腾云跨风，飞升太虚。",
}

local lijueguosi = General(extension, "zhonger_ld_heg__lijueguosi", "qun", 4)
lijueguosi:addCompanions("zhonger_st_heg__jiaxu")
local xiongsuan = fk.CreateActiveSkill{
  name = "zhonger_ld_heg__xiongsuan",
  anim_type = "offensive",
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    if player.dead or target.dead then return false end
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
    if player.dead then return false end
    player:drawCards(3, self.name)
    if target.dead then return false end
    local skills = table.filter(target.player_skills, function(s)
      return s.frequency == Skill.Limited and target:usedSkillTimes(s.name, Player.HistoryGame) > 0
    end)
    if #skills == 0 then return false end
    local skillNames = table.map(skills, function(s)
      return s.name
    end)
    local skill = room:askForChoice(player, skillNames, self.name, "#xiongsuan-reset::" .. target.id)
    room:setPlayerMark(player, "_xiongsuan-turn", {skill, target.id})
  end,
}
local xiongsuan_delay = fk.CreateTriggerSkill{
  name = "#zhonger_ld_heg__xiongsuanDelay",
  visible = false,
  frequency = Skill.Compulsory,
  events = {fk.TurnEnd},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and type(player:getMark("_xiongsuan-turn")) == "table"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skill = player:getMark("_xiongsuan-turn")[1]
    target = room:getPlayerById(player:getMark("_xiongsuan-turn")[2])
    target:addSkillUseHistory(skill, -1)
    room:sendLog{
      type = "#XiongsuanReset",
      from = target.id,
      arg = skill,
    }
  end,
}
xiongsuan:addRelatedSkill(xiongsuan_delay)
lijueguosi:addSkill(xiongsuan)
Fk:loadTranslationTable{
  ['zhonger_ld_heg__lijueguosi'] = '李傕郭汜',
  ["#zhonger_ld_heg__lijueguosi"] = "犯祚倾祸",
  ["designer:zhonger_ld_heg__lijueguosi"] = "千幻",
  ["illustrator:zhonger_ld_heg__lijueguosi"] = "旭",
  ["zhonger_ld_heg__xiongsuan"] = "凶算",
  [":zhonger_ld_heg__xiongsuan"] = "限定技，出牌阶段，你可弃置一张手牌并选择一名角色，你对其造成1点伤害，摸三张牌，选择其一个已发动过的限定技，然后此回合结束前，你令此技能于此局游戏内的发动次数上限+1。",
  ["#xiongsuan-reset"] = "凶算：请重置%dest的一项技能",
  ["#zhonger_ld_heg__xiongsuanDelay2"] = "凶算",
  ["#XiongsuanReset"] = "%from 重置了限定技“%arg”",
  ["$zhonger_ld_heg__xiongsuan1"] = "此战虽凶，得益颇高。",
  ["$zhonger_ld_heg__xiongsuan2"] = "谋算计策，吾二人尚有险招。",
  ["~zhonger_ld_heg__lijueguosi"] = "异心相争，兵败战损……",
}

local cuiyanmaojie = General(extension, "zhonger_ld_heg__cuiyanmaojie", "wei", 3)
local yajun = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__yajun",
  anim_type = "control",
  events = {fk.DrawNCards, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.DrawNCards then
        return true
      else
        return player.phase == Player.Play and not player:isKongcheng() and
          table.find(player.room:getOtherPlayers(player), function(p) return player:canPindian(p) end)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.DrawNCards then
      return true
    else
      local ids = {}
      player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        for _, move in ipairs(e.data) do
          if move.to == player.id and move.toArea == Card.PlayerHand then
            for _, info in ipairs(move.moveInfo) do
              if table.contains(player.player_cards[Player.Hand], info.cardId) then
                table.insertIfNeed(ids, info.cardId)
              end
            end
          end
        end
        return false
      end, Player.HistoryTurn)
      if #ids == 0 then return false end
      local tos, id = player.room:askForChooseCardAndPlayers(player, table.map(table.filter(player.room:getOtherPlayers(player), function(p) return player:canPindian(p) end), Util.IdMapper), 1, 1, tostring(Exppattern{ id = ids }), "#yajun-cm", self.name, true)
      if #tos > 0 and id then
        self.cost_data = {tos[1], id}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawNCards then
      data.n = data.n + 1
    else
      local to = room:getPlayerById(self.cost_data[1])
      local pindian = player:pindian({to}, self.name, Fk:getCardById(self.cost_data[2]))
      if player.dead then return end
      if pindian.results[to.id].winner == player then
        player:drawCards(1, self.name)
        end
      end
  end,
}
cuiyanmaojie:addSkill(yajun)
cuiyanmaojie:addSkill("ld__fengying")

cuiyanmaojie:addCompanions("zhonger_st_heg__caopi")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__cuiyanmaojie"] = "崔琰毛玠",
  ["#zhonger_ld_heg__cuiyanmaojie"] = "日出月盛",
  ["designer:zhonger_ld_heg__cuiyanmaojie"] = "Virgopaladin（韩旭）",
  ["illustrator:zhonger_ld_heg__cuiyanmaojie"] = "兴游",
  ['zhonger_ld_heg__yajun'] = "征辟",
  ["$zhonger_ld_heg__yajun1"] = "跅弛之士，在御之而已。",
  ["$zhonger_ld_heg__yajun2"] = "内不避亲，外不避仇。",
  [":zhonger_ld_heg__yajun"] = "①摸牌阶段，你多摸一张牌；②出牌阶段开始时，你可以用一张本回合获得的牌与一名其他角色拼点，若你：赢，你摸一张牌。",
  ["#yajun-cm"] = "征辟：你可以用一张本回合获得的牌与一名其他角色拼点",
  ["~zhonger_ld_heg__cuiyanmaojie"] = "为世所痛惜，冤哉……",
}

local yujin = General(extension, "zhonger_ld_heg__yujin", "wei", 4)
local jieyue = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__jieyue",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and not player:isKongcheng() and table.find(player.room.alive_players, function(p) return
      p.kingdom ~= "wei"
    end)
  end,
  on_cost = function(self, event, target, player, data)
    local plist, cid = player.room:askForChooseCardAndPlayers(player, table.map(table.filter(player.room.alive_players, function(p) return
      p.kingdom ~= "wei" and p ~= player
    end), Util.IdMapper), 1, 1, ".|.|.|hand", "#zhonger_ld_heg__jieyue-target", self.name, true)
    if #plist > 0 then
      self.cost_data = {plist[1], cid}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = self.cost_data[1]
    local target = room:getPlayerById(to)
    room:moveCardTo(self.cost_data[2], Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
    if H.askCommandTo(player, target, self.name) then
      player:drawCards(0, self.name)
    else
      player:drawCards(3, self.name)
    end
  end
}
yujin:addSkill(jieyue)

Fk:loadTranslationTable{
  ['zhonger_ld_heg__yujin'] = '于禁',
  ["#zhonger_ld_heg__yujin"] = "讨暴坚垒",
  ["designer:zhonger_ld_heg__yujin"] = "官方",
  ["illustrator:zhonger_ld_heg__yujin"] = "biou09",
  ['zhonger_ld_heg__jieyue'] = '节钺',
  [':zhonger_ld_heg__jieyue'] = '准备阶段，你可将一张手牌交给不是魏势力或没有势力的一名角色，对其发起“军令”。若其不执行，你摸三张牌。',

  ["#zhonger_ld_heg__jieyue-target"] = "节钺：你可将一张手牌交给不是魏势力或没有势力的一名角色，对其发起军令",
  ["#zhonger_ld_heg__jieyue_draw"] = "节钺",

  ["$zhonger_ld_heg__jieyue1"] = "奉令无犯，当敌制决！",
  ["$zhonger_ld_heg__jieyue2"] = "质中性一，守执节义，自当无坚不陷。",
  ["~zhonger_ld_heg__yujin"] = "呃，晚节不保……",
}

local wangping = General(extension, "zhonger_ld_heg__wangping", "shu", 4)
local zhonger_ld_heg__jianglue = fk.CreateActiveSkill{
  name = "zhonger_ld_heg__jianglue",
  frequency = Skill.Limited,
  anim_type = "support",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local index = H.startCommand(player, self.name)
    local kingdom = H.getKingdom(player)
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) and p ~= player end), Util.IdMapper)
    local tos = {}
    if #targets > 0 then
      room:doIndicate(player.id, targets)
      room:sortPlayersByAction(targets)
      for _, pid in ipairs(targets) do
        local p = room:getPlayerById(pid)
        if player.dead then break end
        if not p.dead and H.doCommand(p, self.name, index, player) then
          table.insert(tos, pid)
        end
      end
    end
    table.insert(tos, 1, player.id)
    local num = 0
    player:drawCards(1, self.name)
    for _, pid in ipairs(tos) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        if not p.dead then
          if room:recover({
            who = p,
            num = 1,
            recoverBy = player,
            skillName = self.name
          }) then
            num = num + 1
          end
        end
      end
    end
    if num > 0 then player:drawCards(num, self.name) end
  end
}
wangping:addSkill(zhonger_ld_heg__jianglue)
wangping:addSkill("feijun")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__wangping"] = "王平",
  ["#zhonger_ld_heg__wangping"] = "键闭剑门",
  ["illustrator:zhonger_ld_heg__wangping"] = "zoo",
  ["zhonger_ld_heg__jianglue"] = "兵略",
  [":zhonger_ld_heg__jianglue"] = "限定技，出牌阶段，你可对所有与你势力相同的其他角色同时发起“军令”。你回复1点体力并摸两张牌，所有执行“军令”的角色各回复1点体力。然后你摸X张牌（X为以此法执行军令的角色数）。",
  ["$zhonger_ld_heg__jianglue1"] = "奇略兵速，敌未能料之。",
  ["$zhonger_ld_heg__jianglue2"] = "兵略者，明战胜攻取之数，形机之势，诈谲之变。",
  ["~zhonger_ld_heg__wangping"] = "无当飞军，也有困于深林之时……",
}

local fazheng = General(extension, "zhonger_ld_heg__fazheng", "shu", 3)
fazheng:addCompanions("zhonger_st_heg__liubei")
local xuanhuo = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__xuanhuo",
  anim_type = "control",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw and #player:getCardIds{ Player.Hand, Player.Equip } > 1
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#os_ex__xuanhuo-target", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    to:drawCards(2, self.name)
    if player.dead or to.dead then return end
    local targets = table.map(table.filter(room:getOtherPlayers(target), function(p)
      return target:inMyAttackRange(p) end), Util.IdMapper)
    if #targets == 0 then
      if to:isNude() then return end
      local cards = room:askForCardsChosen(player, to, math.min(2, #to:getCardIds("he")), 2, "he", self.name)
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(cards)
      room:obtainCard(player, dummy, false, fk.ReasonPrey)
    else
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#xuanhuo-choose::"..to.id, self.name, false, true)
      local victim
      if #tos > 0 then
        victim = tos[1]
      else
        victim = table.random(targets)
      end
      room:doIndicate(to.id, {victim})
      local use = room:askForUseCard(to, "slash", "slash", "#xuanhuo-slash:"..player.id..":"..victim, true, {must_targets = {victim}})
      if use then
        room:useCard(use)
      else
        if to:isNude() then return end
        local cards = room:askForCardsChosen(player, to, math.min(2, #to:getCardIds("he")), 2, "he", self.name)
        local dummy = Fk:cloneCard("dilu")
        dummy:addSubcards(cards)
        room:obtainCard(player, dummy, false, fk.ReasonPrey)
      end
    end
    return true
  end,
}
fazheng:addSkill("ld__enyuan")
fazheng:addSkill(xuanhuo)

Fk:loadTranslationTable{
  ["zhonger_ld_heg__fazheng"] = "法正",
  ["#zhonger_ld_heg__fazheng"] = "蜀汉的辅翼",
  ["illustrator:zhonger_ld_heg__fazheng"] = "黑白画谱",
  ["zhonger_ld_heg__xuanhuo"] = "眩惑",
  [":zhonger_ld_heg__xuanhuo"] = "摸牌阶段结束时，你可以交给一名其他角色摸两张牌，然后除非该角色对其攻击范围内你选择的另一名角色使用一张【杀】，否则你获得其两张牌。",
  ["#xuanhuo-choose"] = "眩惑：选择令 %dest 使用【杀】的目标",
  ["#xuanhuo-slash"] = "眩惑：你需对 %dest 使用【杀】，否则 %src 获得你两张牌",
  ["#os_ex__xuanhuo-target"] = "你可对一名其他角色发动“眩惑”",
  ["#os_ex__xuanhuo-give"] = "眩惑：交给 %src 两张牌",
  ["os_ex__xuanhuo_extract"] = "%arg获得你两张牌",
  ["@zhonger_ld_heg__xuanhuo_skills-turn"] = "眩惑",
  ["$zhonger_ld_heg__xuanhuo1"] = "收人钱财，替人消灾。",
  ["$zhonger_ld_heg__xuanhuo2"] = "哼，叫你十倍奉还！",
  ["~zhonger_ld_heg__fazheng"] = "汉室复兴，我，是看不到了……",
}

local lukang = General(extension, "zhonger_ld_heg__lukang", "wu", 4, 4, General.Male)
lukang:addSkill("qianjie")
lukang:addSkill("jueyan")
Fk:loadTranslationTable{
  ["zhonger_ld_heg__lukang"] = "陆抗",
  ["#zhonger_ld_heg__lukang"] = "孤柱扶厦",
  ["illustrator:zhonger_ld_heg__lukang"] = "王立雄",
  ["~zhonger_ld_heg__lukang"] = "吾既亡矣，又能存几时...",
}

local wuguotai = General(extension, "zhonger_ld_heg__wuguotai", "wu", 3, 3, General.Female)
local buyi = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__buyi",
  anim_type = "support",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not target:isKongcheng() and player:usedSkillTimes(self.name) == 0 and H.compareKingdomWith(target, player)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#buyi-invoke::"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local id = room:askForCardChosen(player, target, "h", self.name)
    target:showCards({id})
    if target.dead then return end
    if Fk:getCardById(id).type ~= Card.TypeBasic then
      room:throwCard({id}, self.name, target, target)
      if target.dead or not target:isWounded() then return end
      room:recover{
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
  end,
}

wuguotai:addSkill(buyi)
wuguotai:addSkill("ganlu")
wuguotai:addCompanions("zhonger_st_heg__sunjian")

Fk:loadTranslationTable{
  ['zhonger_ld_heg__wuguotai'] = '吴国太',
  ["#zhonger_ld_heg__wuguotai"] = "武烈皇后",
  ["illustrator:zhonger_ld_heg__wuguotai"] = "李秀森",
  ['zhonger_ld_heg__buyi'] = '补益',
  [':zhonger_ld_heg__buyi'] = '每回合限一次，当与你势力相同的角色进入濒死状态时，你可以展示该角色一张手牌，若不为基本牌，则其弃置此牌并回复1点体力。',

  ["#zhonger_ld_heg__buyi-ask"] = "补益：你可对 %dest 发起军令。若来源不执行，则 %src 回复1点体力",

  ["$ganlu_zhonger_ld_heg__wuguotai1"] = "玄德，实乃佳婿呀！", -- 特化
  ["$ganlu_zhonger_ld_heg__wuguotai2"] = "好一个郎才女貌，真是天作之合啊。",
  ["$zhonger_ld_heg__buyi1"] = "有我在，定保贤婿无余！",
  ["$zhonger_ld_heg__buyi2"] = "东吴，岂容汝等儿戏！",
  ["~zhonger_ld_heg__wuguotai"] = "诸位卿家，还请尽力辅佐仲谋啊……",
}

local yuanshu = General(extension, "zhonger_ld_heg__yuanshu", "qun", 4)
yuanshu:addCompanions("zhonger_st_heg__jiling")
local yongsi = fk.CreateTriggerSkill{
  name = "zhonger_ld_heg__yongsi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart, fk.DrawNCards, fk.TargetConfirmed},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self) then return false end
    if event == fk.TargetConfirmed then
      return data.card.trueName == "known_both" and not player:isKongcheng()
    else
      return event == fk.DrawNCards or player.phase == Player.Play
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local card = Fk:cloneCard("known_both")
      local max_num = card.skill:getMaxTargetNum(player, card)
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if not player:isProhibited(p, card) then
          table.insert(targets, p.id)
        end
      end
      if #targets == 0 or max_num == 0 then return end
      local to = room:askForChoosePlayers(player, targets, 1, max_num, "#yongsi__jade_seal-ask", self.name, false)
      if #to > 0 then
        self.cost_data = to
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "control")
      local targets = table.map(self.cost_data, Util.Id2PlayerMapper)
      room:useVirtualCard("known_both", nil, player, targets, self.name)
    elseif event == fk.DrawNCards then
      room:notifySkillInvoked(player, self.name, "drawcard")
      data.n = data.n + 1
    end
  end,
}
yuanshu:addSkill(yongsi)
yuanshu:addSkill("ld__weidi")

Fk:loadTranslationTable{
  ['zhonger_ld_heg__yuanshu'] = '袁术',
  ["#zhonger_ld_heg__yuanshu"] = "仲家帝",
  ["illustrator:zhonger_ld_heg__yuanshu"] = "YanBai",
  ['zhonger_ld_heg__yongsi'] = "庸肆",
  [':zhonger_ld_heg__yongsi'] = "锁定技，你摸牌阶段多摸一张牌，且出牌阶段开始时视为使用【知己知彼】。",
  ["#yongsi__jade_seal-ask"] = "庸肆：你视为使用一张【知己知彼】",
  ["$zhonger_ld_heg__yongsi1"] = "天下，即将尽归吾袁公路！",
  ["$zhonger_ld_heg__yongsi2"] = "朕今日雄踞淮南，明日便可一匡天下。",
  ["$ld__weidi_zhonger_ld_heg__yuanshu1"] = "传国玉玺在手，朕语便是天言！",
  ["$ld__weidi_zhonger_ld_heg__yuanshu2"] = "传朕旨意，诸部遵旨即可。",
  ["~zhonger_ld_heg__yuanshu"] = "仲朝国祚，本应千秋万代，薪传不息……",
}

local zhangxiu = General(extension, "zhonger_ld_heg__zhangxiu", "qun", 4)
local xiongluan = fk.CreateActiveSkill{
  name = "zhonger_ld_heg__xiongluan",
  anim_type = "offensive",
  target_num = 1,
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
    (#player:getAvailableEquipSlots() > 0 or not table.contains(player.sealedSlots, Player.JudgeSlot))
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return Self.id ~= to_select
  end,
  on_use = function(self, room, effect)
    local to = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local eqipSlots = player:getAvailableEquipSlots()
    if not table.contains(player.sealedSlots, Player.JudgeSlot) then
      table.insert(eqipSlots, Player.JudgeSlot)
    end
    room:abortPlayerArea(player, eqipSlots)
    room:addPlayerMark(to, "@@zhonger_ld_heg__xiongluan-turn")
    local targetRecorded = type(player:getMark("zhonger_ld_heg__xiongluan_target-turn")) == "table" and player:getMark("zhonger_ld_heg__xiongluan_target-turn") or {}
    table.insertIfNeed(targetRecorded, to.id)
    room:setPlayerMark(player, "zhonger_ld_heg__xiongluan_target-turn", targetRecorded)
  end,
}
local xiongluan_prohibitt = fk.CreateProhibitSkill{
  name = "xiongluan_prohibitt",
  prohibit_use = function(self, player, Jink)
    if player:getMark("@@zhonger_ld_heg__xiongluan-turn") > 0 and not player.dying then
      local subcards = Jink:isVirtual() and Jink.subcards or {Jink.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, Jink)
    if player:getMark("@@zhonger_ld_heg__xiongluan-turn") > 0 and not player.dying then
      local subcards = Jink:isVirtual() and Jink.subcards or {Jink.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
}
local xiongluan_targetmod = fk.CreateTargetModSkill{
  name = "#xiongluan_targetmod2",
  bypass_times = function(self, player, skill, scope, card, to)
    if card and to then
      local targetRecorded = player:getMark("zhonger_ld_heg__xiongluan_target-turn")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
  bypass_distances = function(self, player, skill, card, to)
    if card and to then
      local targetRecorded = player:getMark("zhonger_ld_heg__xiongluan_target-turn")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
}
xiongluan:addRelatedSkill(xiongluan_targetmod)
xiongluan:addRelatedSkill(xiongluan_prohibitt)
zhangxiu:addSkill(xiongluan)
zhangxiu:addSkill("congjian")
zhangxiu:addCompanions("zhonger_st_heg__jiaxu")
Fk:loadTranslationTable{
  ['zhonger_ld_heg__zhangxiu'] = '张绣',
  ["#zhonger_ld_heg__zhangxiu"] = "北地枪王",
  ["xiongluan_prohibitt"] = "雄乱",
  ["designer:zhonger_ld_heg__zhangxiu"] = "官方",
  ["illustrator:zhonger_ld_heg__zhangxiu"] = "青岛磐蒲",
  ["zhonger_ld_heg__xiongluan"] = "雄乱",
  [":zhonger_ld_heg__xiongluan"] = "限定技，出牌阶段，你可以废除你的判定区和装备区，然后指定一名其他角色。直到回合结束，你对其使用牌无距离和次数限制，其不能使用和打出手牌响应你的牌。",
  ["@@zhonger_ld_heg__xiongluan-turn"] = "雄乱",
  ["$zhonger_ld_heg__xiongluan1"] = "北地枭雄，乱世不败！！",
  ["$zhonger_ld_heg__xiongluan2"] = "雄据宛城，虽乱世可安！",
  ['~zhonger_ld_heg__zhangxiu'] = '若失文和，吾将何归？',
}

return extension
